<?php
namespace control;


class salesStatisticsClass extends adIndexClass
{
    private const title = '客户销售统计';
    private const page = 'salesStatistics';
    private const table = 'kehu';
    private const tableAddr = 'sales_contract_address'; # 地址表

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'monthDate' => [
                        'name'  => '月份',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "客户编码",
                        'width' => 150,
                    ],
                    'companyName'          => [
                        'name'  => '客户名称',
                        'width' => 200,
                    ],
                    'manager'  => [
                        'name'  => "提醒人",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'average_weight'         => [
                        'name'  => '月平均重量',
                        'width' => 150,
                    ],
                    'month_weight'          => [
                        'name'  => '本月重量',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'status'          => [
                        'name'  => '状态',
                        'width' => 100,
                        'sort' => 1,
                    ],
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $array = [
            [
                [
                    "客户编码" => text(array("name" => "companyName")),
                    "客户名称"   => text(array("name" => "label")),
//                    "状态" => text(array("name" => "contactName")),
                ],
            ]
        ];
        //生成查询表单
        $html = $this->tableShow($array);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "companyName" => $this->post('companyName'),//客户名称
        );
        //全等查询数组
        $equal = array(
            'coid'=>self::$coid,
            "manager" => self::$stid,
            "orderNo" => $this->post('orderNo'),
        );
        //公私客
        $and = " and manager !=''";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => "kehu", "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //当月
        $new_start_time = date('Y-m-01');
        $start_time = mktime(0, 0, 0, date('m')-3, 01, date('Y'));
        $start_time = date('Y-m-d', $start_time);
        $end_time   = mktime(0, 0, 0, date('m'), 01, date('Y'));
        $end_time = date('Y-m-d', $end_time);
        //上月
        $up_new_start_time = date('Y-m-01',strtotime('-1 month'));
        $up_start_time = mktime(0, 0, 0, date('m')-4, 01, date('Y'));
        $up_start_time = date('Y-m-d', $up_start_time);
        $up_end_time   = mktime(0, 0, 0, date('m')-1, 01, date('Y'));
        $up_end_time = date('Y-m-d', $up_end_time);
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            //三月前发货单//
            $new_start_order = query('sale_send_order_detail',"orderId in (SELECT id FROM sale_send_order WHERE (recordDate > '{$new_start_time}') AND khid = '{$array['khid']}')",'num');
            $new_start_order = array_sum($new_start_order);
            $up_new_start_order = query('sale_send_order_detail',"orderId in (SELECT id FROM sale_send_order WHERE (recordDate < '{$new_start_time}') AND recordDate >= '{$up_new_start_time}') AND khid = '{$array['khid']}')",'num');
            $up_new_start_order = array_sum($up_new_start_order);
            $start_order = query('sale_send_order_detail',"orderId in (SELECT id FROM sale_send_order WHERE (recordDate BETWEEN '{$start_time}' AND '{$end_time}') AND khid = '{$array['khid']}')",'num');
            $start_order = array_sum($start_order);
            $up_start_order = query('sale_send_order_detail',"orderId in (SELECT id FROM sale_send_order WHERE (recordDate BETWEEN '{$up_start_time}' AND '{$up_end_time}') AND khid = '{$array['khid']}')",'num');
            $up_start_order = array_sum($up_start_order);
            //三个月前退货单
            $new_end_order = query('sale_refund_order_detail',"orderId in (SELECT id FROM sale_refund_order WHERE (recordDate > '{$new_start_time}') AND khid = '{$array['khid']}')",'num');
            $new_end_order = array_sum($new_end_order);
            $up_new_end_order = query('sale_refund_order_detail',"orderId in (SELECT id FROM sale_refund_order WHERE (recordDate < '{$new_start_time}') AND recordDate >= '{$up_new_start_time}') AND khid = '{$array['khid']}')",'num');
            $up_new_end_order = array_sum($up_new_end_order);
            $end_order = query('sale_refund_order_detail',"orderId in (SELECT id FROM sale_refund_order WHERE (recordDate BETWEEN '{$start_time}' AND '{$end_time}') AND khid = '{$array['khid']}')",'num');
            $up_end_order = query('sale_refund_order_detail',"orderId in (SELECT id FROM sale_refund_order WHERE (recordDate BETWEEN '{$up_start_time}' AND '{$up_end_time}') AND khid = '{$array['khid']}')",'num');
            $end_order = array_sum($end_order);
            $up_end_order = array_sum($up_end_order);
            for ($i=1;$i<2;$i++){
                $row = [];
                foreach ($installSearch['key'] as $key) {
                    switch ($key) {
                        case "monthDate":
                            if($i == 1){
                                $row[] = date('Y-m',strtotime('-1 month'));
                            }else{
                                $row[] = date('Y-m');
                            }
                            break;
                        case "average_weight":
                            if($i == 1){
                                $row[] = $up_start_order - $up_end_order;
                            }else{
                                $row[] = $start_order - $end_order;
                            }
                            break;
                        case "month_weight":
                            if($i == 1){
                                $row[] = $up_new_start_order - $up_new_end_order;
                            }else{
                                $row[] = $new_start_order - $new_end_order;
                            }
                            break;
                        case "status":
                            //最后的一条跟进记录
                            if($i == 1){
                                $row[] = ($up_new_start_order - $up_new_end_order) <= ($up_new_start_order - $up_new_end_order) ? '正常' : '下降';
                            }else{
                                $row[] = ($start_order - $end_order) <= ($new_start_order - $new_end_order) ? '正常' : '下降';
                            }
                            break;
                        default:
                            $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                    }
                }
                $body[] = $row;
            }

        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出 todo
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('client.exportData.power');
        }   else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "khid in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $pool = query('pool', " id = '$array[poolId]'");
                $tags = '';
                $kehu_label = find(array('table' => 'kehu_label', 'where'=>"targetId = '$array[khid]' order by list asc"));
                foreach ($kehu_label['array'] as $val) {
                    $tag_detail = query('tag_detail', "id = '$val[tag_detail_id]'");
                    $tags .= $tag_detail['name'].',';
                }
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '客户名称'=>$array['companyName'],
                            '性质'=>$array['nature'],
                            '常用联系人姓名'=>$array['contactName'],
                            '常用联系人职务'=>$array['contactIdentity'],
                            '常用联系人手机'=>$array['contactTel'],
                            '常用联系人电话'=>$array['landline'],
                            '常用联系人微信'=>$array['contactWx'],
                            '常用联系人QQ'=>$array['contactQQ'],
                            '生日'=>$array['birthDay'],
                            '网址'=>$array['website'],
                            '邮箱'=>$array['email'],
                            '地址'=>$array['address'],
                            '客户级别'=>$array['level'],
                            '客户类别'=>$array['classify'],
                            '所属行业'=>$array['scale'],
                            '人员规模'=>$array['source'],
                            '来源'=>$array['workFlow'],
                            '跟进状态'=>$array['followTime'],
                            '下次跟进时间'=> '',
                            '标签'=>$tags,
                            '所属客户池'=> $pool['name'],
                            '负责人'=> self::findStaff($array['manager']),
                            '协作人'=> clueClass::showMember($array['collaborator'], 2),
                            '开票公司'=>$array['invoiceCompany'],
                            '开户行'=>$array['companyBank'],
                            '银行账号'=>$array['companyBankNum'],
                            '注册地址、电话'=>$array['companyAddress'],
                            '纳税人识别号'=>$array['companyNum'],
                            '邮寄地址'=>$array['postAddress'],
                            '备注'=>$array['text'],
                            '创建人'=> self::findStaff($array['stid']),
                            '更新时间'=>$array['updateTime'],
                            '创建时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('client.exportData.text'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('client.exportData.fileName').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

}